package com.sinosoft.framework.filter;


import javax.servlet.*;
import java.io.IOException;

/**
 * @author ZZZ
 * @version 1.0
 * @desc 编码过滤器
 * @date 2018/6/19 0019
 */
public class CharacterEncodingFilter implements Filter {

    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器......");
        encoding = filterConfig.getInitParameter("encoding");
        System.out.println("encoding is : " + encoding);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String reqEncoding = servletRequest.getCharacterEncoding();
        String respEncoding = servletResponse.getCharacterEncoding();
        if (reqEncoding == null || !"UTF-8".equalsIgnoreCase(reqEncoding)) {
            servletRequest.setCharacterEncoding(encoding);
        }
        if (respEncoding == null || !"UTF-8".equalsIgnoreCase(respEncoding)) {
            servletResponse.setCharacterEncoding(encoding);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("销毁过滤器......");
    }
}
